<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js"></script>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
				list-style: none;
			}

			ul {
				width: 310px;
				background-color: #421C0F;
				display: flex;
				flex-wrap: wrap;
				margin: 30px auto;
				border: 5px solid #421C0F;
				border-radius: 5px;
			}

			li {
				width: 100px;
				height: 100px;
				background-color: #E4B77C;
				border: 1px solid #421C0F;
				text-align: center;
				line-height: 100px;
				font-weight: bold;
			}

			button {
				padding: 10px 20px;
				background: #421C0F;
				border-color: #421C0F;
				color: #fff;
				border-radius: 5px;
				display: block;
				margin: 10px auto;
			}

			.blank {
				opacity: 0;
			}

			.list-move {
				transition: .5s;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<h2 align=center> {{m<10?'0'+m:m}}:{{s<10?'0'+s:s}} </h2>
			<transition-group tag="ul" name="list">
				<li :class="item==0?'blank':''" v-for='(item,index) in list' :key='item' @click="move(index)">
					{{item>0?item:''}}
				</li>
			</transition-group>
			<button @click="start">开始游戏</button>
		</div>
		<script>
			Vue.createApp({
				data() {
					return {
						list: [1, 2, 3, 4, 5, 6, 7, 8, 0], //0:空方块
						mark: [1, 2, 3, 4, 5, 6, 7, 8, 0],
						flag: 0, //开关
						m: 0,
						s: 0,
						timer: null
					}
				},
				methods: {
					startTime() { //计时器
						var timer = setInterval(() => {
							this.s++
							if (this.s >= 60) {
								this.m++
								this.s = 0
							}
						}, 1000)
					},
					start() { //开始游戏  打乱顺序
						this.list.sort(() => Math.random() - 0.5)
						this.flag = 1
						this.s = 0
						this.m = 0
						this.startTime()
					},
					move(i) { //移动方块
						if (!this.flag) return
						var neb = [i - 3, i + 3, i - 1, i + 1] //上下左右方块的下标
						if (parseInt(neb[2] / 3) != parseInt(i / 3)) {
							neb[2] = -1 //判断左边方块是不是同一行
						}
						if (parseInt(neb[3] / 3) != parseInt(i / 3)) {
							neb[3] = -1 //判断右边方块是不是同一行
						}
						for (let j = 0; j < 4; j++) {
							let next = neb[j]
							if (next >= 0 && this.list[next] == 0) {
								// 找到空白方块
								this.list[next] = this.list[i]
								this.list[i] = 0
								break
							}
						}
						if (this.check()) {
							clearInterval(this.timer)
							setTimeout(() => {
								alert('挑战成功!')
							}, 10)
						}
					},
					check() { //判断是否成功
						for (let i = 0; i < 9; i++) {
							if (this.list[i] != this.mark[i]) {
								return false
							}
						}
						return true //挑战成功
					}
				}
			}).mount("#app")
		</script>
	</body>
</html>